import React, { useEffect, useState } from "react";
import { Table, Tag, message, Spin, Button, Modal, Form, Input, InputNumber, DatePicker, Select, Popconfirm } from "antd";
import type { ColumnsType } from "antd/es/table";
import dayjs from "dayjs";

interface IAMData {
  key: string;
  id: number;
  username: string;
  idcard: string;
  userstate: string;
  createtime: string;
  pay: number;
}

const IAM_View: React.FC = () => {
  const [data, setData] = useState<IAMData[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [pageIndex, setPageIndex] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [editModalOpen, setEditModalOpen] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [editLoading, setEditLoading] = useState(false);
  const [searchUserName, setSearchUserName] = useState<string>("");

  // 获取数据
  const fetchData = (page = pageIndex, size = pageSize, userName = searchUserName) => {
    setLoading(true);
    const params = new URLSearchParams({
      PageIndex: String(page),
      PageSize: String(size),
    });
    if (userName) params.append("UserName", userName);
    fetch(`http://localhost:5017/api/IAM/ShowIAM?${params.toString()}`)
      .then(res => res.json())
      .then((res) => {
        const arr = Array.isArray(res.items) ? res.items : [];
        const tableData = arr.map((item: any, idx: number) => ({
          key: String((page - 1) * size + idx + 1),
          id: item.id,
          username: item.userName,
          idcard: item.idCard,
          userstate: item.userState,
          createtime: item.createTime,
          pay: item.pay,
        }));
        setData(tableData);
        setTotal(res.total || 0);
      })
      .catch(() => {
        message.error("获取数据失败");
      })
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    fetchData(pageIndex, pageSize);
    // eslint-disable-next-line
  }, [pageIndex, pageSize]);

  // 查询按钮点击事件
  const handleSearch = () => {
    setPageIndex(1); // 查询时重置到第一页
    fetchData(1, pageSize, searchUserName);
  };

  // 提交表单
  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      // 格式化时间
      values.createTime = values.createTime.format("YYYY-MM-DDTHH:mm:ss");
      // 字段名转为后端格式
      const postData = {
        userName: values.username,
        idCard: values.idcard,
        userState: values.userstate,
        createTime: values.createTime,
        pay: values.pay,
      };
      
      console.log('发送新增数据:', postData);
      
      const res = await fetch("http://localhost:5017/api/IAM/AddIAM", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(postData),
      });
      
      console.log('新增响应状态:', res.status);
      
      if (res.ok) {
        const result = await res.json();
        console.log('新增响应数据:', result);
        alert("添加成功");
        setModalOpen(false);
        form.resetFields();
        fetchData();
      } else {
        const errorText = await res.text();
        console.error('新增失败:', res.status, errorText);
        message.error(`添加失败: ${res.status} ${errorText}`);
      }
    } catch (error) {
      console.error('新增异常:', error);
      message.error(`添加异常: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  };

  // 单条删除
  const handleDelete = async (id: number) => {
    try {
      console.log('删除ID:', id);
      
      const res = await fetch("http://localhost:5017/api/IAM/DelIam", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id: String(id) }),
      });
      
      console.log('删除响应状态:', res.status);
      
      if (res.ok) {
        const result = await res.json();
        console.log('删除响应数据:', result);
        alert("删除成功");
        fetchData();
      } else {
        const errorText = await res.text();
        console.error('删除失败:', res.status, errorText);
        message.error(`删除失败: ${res.status} ${errorText}`);
      }
    } catch (error) {
      console.error('删除异常:', error);
      message.error(`删除异常: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  };

  // 编辑弹窗回显
  const handleEdit = async (id: number) => {
    setEditLoading(true);
    setEditingId(id);
    try {
      const res = await fetch(`http://localhost:5017/api/IAM/GetIAM?Id=${id}`);
      if (res.ok) {
        const result = await res.json();
        console.log('编辑回显数据', result);
        form.resetFields();
        form.setFieldsValue({
          username: result.data.userName,
          idcard: result.data.idCard,
          userstate: result.data.userState,
          createTime: dayjs(result.data.createTime),
          pay: result.data.pay,
        });
        setEditModalOpen(true);
      } else {
        message.error('获取详情失败');
      }
    } catch {
      message.error('获取详情异常');
    } finally {
      setEditLoading(false);
    }
  };

  // 编辑提交
  const handleEditOk = async () => {
    if (!editingId) return;
    try {
      const values = await form.validateFields();
      values.createTime = values.createTime.format("YYYY-MM-DDTHH:mm:ss");
      const putData = {
        id: editingId,
        userName: values.username,
        idCard: values.idcard,
        userState: values.userstate,
        createTime: values.createTime,
        pay: values.pay,
      };
      setEditLoading(true);
      const res = await fetch("http://localhost:5017/api/IAM/UpdateIAM", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(putData),
      });
      if (res.ok) {
        message.success("编辑成功");
        setEditModalOpen(false);
        setEditingId(null);
        form.resetFields();
        fetchData();
      } else {
        const errorText = await res.text();
        message.error(`编辑失败: ${res.status} ${errorText}`);
      }
    } catch (error) {
      message.error(`编辑异常: ${error instanceof Error ? error.message : '未知错误'}`);
    } finally {
      setEditLoading(false);
    }
  };

  // columns 必须在组件内部定义，且 handleDelete 可见
  const columns: ColumnsType<IAMData> = [
    {
      title: "序号",
      dataIndex: "key",
      key: "key",
      width: 80,
    },
    {
      title: "名称",
      dataIndex: "username",
      key: "username",
    },
    {
      title: "身份证号",
      dataIndex: "idcard",
      key: "idcard",
    },
    {
      title: "匹配状态",
      dataIndex: "userstate",
      key: "userstate",
      render: (text: string) => <Tag color="green">{text}</Tag>,
    },
    {
      title: "提交时间",
      dataIndex: "createtime",
      key: "createtime",
      render: (text: string) => text ? dayjs(text).format("YYYY-MM-DD HH:mm") : "-",
    },
    {
      title: "费用",
      dataIndex: "pay",
      key: "pay",
      render: (text: number) => (
        <span style={{ color: "#ff4d4f", background: "#fff1f0", padding: "2px 8px", borderRadius: 4 }}>{text.toFixed(2)}</span>
      ),
    },
    {
      title: "操作",
      key: "action",
      width: 100,
      render: (_, record) => (
        <div style={{ display: 'flex', gap: 8 }}>
          <Button 
            style={{
              background: '#faad14',
              color: '#fff',
              border: 'none',
              height: 32,
              minWidth: 64,
              fontWeight: 500,
              borderRadius: 6,
              padding: '0 16px',
            }}
            onClick={() => handleEdit(record.id)}
          >编辑</Button>
          <Popconfirm title="确认删除该条数据？" onConfirm={() => handleDelete(record.id)}>
            <Button 
              type="primary" 
              danger
              style={{
                height: 32,
                minWidth: 64,
                fontWeight: 500,
                borderRadius: 6,
                padding: '0 16px',
              }}
            >删除</Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  return (
    <div style={{ background: "#fff", padding: 16 }}>
      <div style={{ marginBottom: 16, display: 'flex', gap: 8 }}>
        <Input
          placeholder="请输入用户名称"
          value={searchUserName}
          onChange={e => setSearchUserName(e.target.value)}
          onPressEnter={handleSearch}
          style={{ width: 200 }}
        />
        <Button type="primary" onClick={handleSearch}>查询</Button>
        <Button type="primary" onClick={() => setModalOpen(true)}>
          新增
        </Button>
      </div>
      {loading ? (
        <Spin />
      ) : (
        <Table
          dataSource={data}
          columns={columns}
          pagination={{
            current: pageIndex,
            pageSize: pageSize,
            total: total,
            showSizeChanger: true,
            onChange: (page, size) => {
              setPageIndex(page);
              setPageSize(size);
            },
            showTotal: (t) => `共 ${t} 条`
          }}
          bordered
          rowKey="id"
        />
      )}
      <Modal
        title="新增身份校验"
        open={modalOpen}
        onOk={handleOk}
        onCancel={() => setModalOpen(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item label="名称" name="username" rules={[{ required: true, message: "请输入名称" }]}> 
            <Input />
          </Form.Item>
          <Form.Item label="身份证号" name="idcard" rules={[{ required: true, message: "请输入身份证号" }]}> 
            <Input />
          </Form.Item>
          <Form.Item label="匹配状态" name="userstate" rules={[{ required: true, message: "请选择匹配状态" }]}> 
            <Select>
              <Select.Option value="匹配成功">匹配成功</Select.Option>
              <Select.Option value="匹配失败">匹配失败</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item label="提交时间" name="createTime" rules={[{ required: true, message: "请选择提交时间" }]} initialValue={dayjs()}>
            <DatePicker showTime style={{ width: "100%" }} />
          </Form.Item>
          <Form.Item label="费用" name="pay" rules={[{ required: true, message: "请输入费用" }]}> 
            <InputNumber min={0} style={{ width: "100%" }} />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="编辑身份校验"
        open={editModalOpen}
        onOk={handleEditOk}
        onCancel={() => { setEditModalOpen(false); setEditingId(null); }}
        confirmLoading={editLoading}
      >
        <Form form={form} layout="vertical">
          <Form.Item label="名称" name="username" rules={[{ required: true, message: "请输入名称" }]}> 
            <Input />
          </Form.Item>
          <Form.Item label="身份证号" name="idcard" rules={[{ required: true, message: "请输入身份证号" }]}> 
            <Input />
          </Form.Item>
          <Form.Item label="匹配状态" name="userstate" rules={[{ required: true, message: "请选择匹配状态" }]}> 
            <Select>
              <Select.Option value="匹配成功">匹配成功</Select.Option>
              <Select.Option value="匹配失败">匹配失败</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item label="提交时间" name="createTime" rules={[{ required: true, message: "请选择提交时间" }]}> 
            <DatePicker showTime style={{ width: "100%" }} />
          </Form.Item>
          <Form.Item label="费用" name="pay" rules={[{ required: true, message: "请输入费用" }]}> 
            <InputNumber min={0} style={{ width: "100%" }} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default IAM_View;
